package com.swapper.math.fsa;

import java.util.Arrays;

public final class Table {
  private final String[][] table;
  private final int rows;
  private final int cols;

  public Table(int rows, int cols) {
    this.rows = rows;
    this.cols = cols;
    table = new String[rows][cols];
    for (int i = 0; i < rows; ++i) {
      table[i] = new String[cols];
      for (int j = 0; j < cols; ++j) {
        table[i][j] = "";
      }
    }
  }

  public void set(int row, int col, String value) {
    table[row][col] = value;
  }

  @Override
  public String toString() {
    int[] maxTabs = new int[cols];
    for (int j = 0; j < cols; ++j) {
      maxTabs[j] = 0;
      for (int i = 0; i < rows; ++i) {
        maxTabs[j] = Math.max(maxTabs[j], table[i][j].length() / 4 + 1);
      }
    }
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < rows; ++i) {
      for (int j = 0; j < cols; ++j) {
        String s = table[i][j];
        if (j == cols - 1) {
          builder.append(s);
        } else {
          int count = Math.max(1, maxTabs[j] - s.length() / 4 + 1);
          char[] chars = new char[count];
          Arrays.fill(chars, '\t');
          builder.append(s).append(new String(chars));
        }
      }
      builder.append('\n');
    }
    return builder.toString();
  }
}
